/**
 * xmpp数据访问封装，提供基本的好友维护，消息接收分发管理
 * @author stone
 */
(function(){
	var BOSH_SERVICE = '/xmpp-httpbind';
	var BOSH_SERVICE_IP = "58.215.190.135";
	var connection = null;
	var loginCallBack=function(){};
	var userInfo={};
	//事件监听
	var listerHander={
		onMessage:function(msg){
		},
		onIq:function(iq){
		},
		onPresence:function(opt){
		}
	};
	
	/**
	 * 初始化连接信息
	 * @param {} opt
	 * 		BOSH_SERVICE:服务
	 * 		BOSH_SERVICE_IP:openfire 服务器地址
	 */
	function _initConnection(opt){
		BOSH_SERVICE = opt.BOSH_SERVICE;
		BOSH_SERVICE_IP = opt.BOSH_SERVICE_IP;
		
		connection = new Strophe.Connection(BOSH_SERVICE);
		connection.xmlInput = function (data) { console.log('RECV: '); console.log(data); };
		connection.xmlOutput = function (data) {console.log('SEND: '); console.log(data); };
	}	 
	
	/**
	 * 添加用户
	 * @param {} opt
	 * 		name:登陆用户名
	 * 		password:登陆用户密码
	 */
	function _login(opt){
			loginCallBack = opt.callback;
			
			userInfo.jid = opt.name+"@"+BOSH_SERVICE_IP+"/web";
			userInfo.id = (opt.name+"@"+BOSH_SERVICE_IP).replace(/@/,"at").replace(/\./g,"dian");;
			userInfo.node = opt.name;
			//裸jid
			userInfo.bareJid=opt.name+"@"+BOSH_SERVICE_IP;
			//登陆资源
			userInfo.resource="web";
			//登陆资源服务域名
			userInfo.domain=BOSH_SERVICE_IP;
			
			connection.connect(userInfo.jid,opt.password,onConnect);
	}
	
	function log(msg) 
	{
	   // $('#log').append('<div></div>').append(document.createTextNode(msg));
	}
	function onConnect(status) {
		if (status == Strophe.Status.CONNECTING) {
			console.log('Strophe is connecting.');
		} else if (status == Strophe.Status.CONNFAIL) {
			console.log('Strophe failed to connect.');
			$('#connect').get(0).value = 'connect';
		} else if (status == Strophe.Status.DISCONNECTING) {
			console.log('Strophe is disconnecting.');
		} else if (status == Strophe.Status.DISCONNECTED) {
			console.log('Strophe is disconnected.');
			$('#connect').get(0).value = 'connect';
		} else if (status == Strophe.Status.CONNECTED) {
			connection.addHandler(onMessage, null, 'message', null, null, null);
			connection.addHandler(onPresence, null, 'presence', null, null, null);
			connection.addHandler(onIq, null, 'iq', null, null, null);
			
			loginCallBack({user:userInfo})
			_sendState({show:"online"});
			getFriends();
		}
	}
	
	
	
	/**
	 * 得到朋友列表
	 */
	function getFriends(){
		var iq = $iq({type:"get"});
		iq.cnode(Strophe.xmlElement("query",{xmlns:'jabber:iq:roster'}));
		connection.send(iq.tree());
	}
	/**
	 * 添加用户
	 * @param {} opt
	 * 		name:昵称
	 * 		username:用户名称
	 * 		email:邮箱
	 * 		password:密码
	 */
	function addUser(opt){
		
	   var iq = $iq({type:"set",to:BOSH_SERVICE_IP}).c("query",{xmlns:"jabber:iq:register"})
	   .c("username",{}).t(opt.username).up()
	   .c("email",{}).t(opt.email).up()
	   .c("name",{}).t(opt.name).up()
	   .c("password",{}).t(opt.password);
	    connection.send(iq.tree());
		console.log(iq.tree());
	}
	/**
	 * 订阅（添加朋友）请求
	 * @param {} opt
	 * 		to:你想订阅的人的jid
	 */
	function addFriend(opt){
		var pres = $pres({to:opt.to+"@"+BOSH_SERVICE_IP,type:"subscribe"});
		connection.send(pres.tree());
	}
	/**
	 * 取消订阅（移除好友）请求
	 * @param {} opt
	 *		 to:你想取消订阅的人的jid
	 */
	function removeFriend(opt){
		var pres = $pres({to:opt.to+"@"+BOSH_SERVICE_IP,type:"unsubscribe"});
		connection.send(pres.tree());
	}
	/**
	 * 同意订阅请求
	 * @param {} opt
	 * 		 to:同意别人好友请求的jid
	 */
	function agreeAddFriended(opt){
		var pres = $pres({to:opt.to+"@"+BOSH_SERVICE_IP,type:"subscribed"});
		connection.send(pres.tree());
	}
	/**
	 * 拒绝订阅请求
	 * @param {} opt
	 * 		 to:拒绝别人好友请求的jid
	 */
	function rejectAddFriended(opt){
		var pres = $pres({to:opt.to+"@"+BOSH_SERVICE_IP,type:"unsubscribed"});
		connection.send(pres.tree());
	}
	/**
	 * 加入房间
	 * @param {} opt
	 * 		room:房间名称
	 * 		nikname:加入房间的时候的昵称
	 */
	function _joinRoom(opt){
		var pres = $pres({to:opt.room+"@conference."+BOSH_SERVICE_IP+"/"+opt.nikname})
		.c("x",{xmlns:"http://jabber.org/protocol/muc"});
		connection.send(pres.tree());
	}
	
	/**
	 * 改变自己的状态
	 * @param {} opt
	 */
	function _sendState(opt){
		var pres;
		if(opt.type){
			pres= $pres({type:opt.type})
		}else{ 
			pres= $pres();
			if(opt.show){
				pres.c("show").t(opt.show).up();
			}
			if(opt.status){
				pres.c("status").t(opt.status).up();
			}
			if(opt.priority){
				pres.c("priority").t(opt.priority) ;
			}
		}
		connection.send(pres.tree());
	} 
	
	/**
	 * 发送消息
	 * @param {} opt
	 * 		to:发送对象
	 * 		from:发送消息着
	 * 		type:发送消息类型  chat|groupchat
	 */
	function sendMessage(opt){
			var bodyText = opt.body;
			delete opt.body;
			var reply = $msg(opt).c("body").t(bodyText);
			connection.send(reply.tree());
	}
	
	function getJid(name){
		return name+"@"+BOSH_SERVICE_IP;
	}
	
	/**
	 * 得到jid的详细信息对象
	 */
	function _getJidInfo(jid){
		var obj={};
		obj.jid = jid;
		obj.node=Strophe.getNodeFromJid(jid);
		//裸jid
		obj.bareJid=Strophe.getBareJidFromJid(jid);
		obj.id=obj.bareJid.replace(/@/,"at").replace(/\./g,"dian");
		//登陆资源
		obj.resource=Strophe.getResourceFromJid(jid);
		//登陆资源服务域名
		obj.domain=Strophe.getDomainFromJid(jid);
		
		return obj;
	}
	
	function onIq(msg) {
		console.log("查询iq");
		var items = msg.firstElementChild.childNodes;
		var friendList = [];
		for(var i=0,n=items.length;i<n;i++){
			var item = items[i];
			var jid = item.getAttribute("jid");
			var obj = _getJidInfo(jid);
			obj.subscription=item.getAttribute("subscription");
			if(item.firstElementChild){
				obj.group = item.firstElementChild.textContent;
			}
			friendList.push(obj); 
		}
		listerHander.onIq(friendList);
		return true; 
	}
	/**
	 * 状态改变处理程序
	 * @param {} msg
	 * @return {Boolean}
	 */
	function onPresence(msg) {
		var obj={};
		obj.to = _getJidInfo(msg.getAttribute('to'));
		obj.from = _getJidInfo(msg.getAttribute('from'));
		obj.type = msg.getAttribute('type');
		var ext = msg.childNodes;
		
		for(var i=0,n=ext.length;i<n;i++){
			obj[ext[i].tagName]=ext[i].textContent;
		}
		
		listerHander.onPresence(obj);
		return true; 
	}
	function onMessage(msg) {
		var obj={};
		obj.to = _getJidInfo(msg.getAttribute('to'));
		obj.from = _getJidInfo(msg.getAttribute('from'));
		obj.type = msg.getAttribute('type');
		obj.body = msg.getElementsByTagName('body')[0].textContent;
	
		listerHander.onMessage(obj);
		return true; 
	}
	
	
	
	function _listenerHander(opt){
		$.extend(listerHander,opt);
		listerHander = opt;
	}
	
	
	/**
	 * 得到当前登录用户信息
	 */
	function _getUserInfo(){
		return userInfo;
	}
	window.xmpp = {
		init:_initConnection,
		login:_login,
		listenerHander:_listenerHander,
		sendStatus:_sendState,
		sendMsg:sendMessage,
		getUserInfo:_getUserInfo,
		joinRoom:_joinRoom
	};
})();